package com.hexun.dubbo;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import javax.ws.rs.client.ClientResponseContext;
import javax.ws.rs.client.ClientResponseFilter;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.ReaderInterceptor;
import javax.ws.rs.ext.ReaderInterceptorContext;
import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;
import java.io.IOException;

/**
 * @author yuanyue
 */
//@Priority(Priorities.USER)
public class RestTraceFilter implements
        ClientRequestFilter, ClientResponseFilter,
        ReaderInterceptor, WriterInterceptor,
        ContainerRequestFilter, ContainerResponseFilter {


    /**
     * before
     */
    public void filter(ContainerRequestContext requestContext) throws IOException {

    }

    /**
     * after
     *
     * @param containerRequestContext
     * @param containerResponseContext
     * @throws IOException
     */
    public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException {
//        Request request = containerRequestContext.getRequest();
//        if (request != null && request instanceof HttpServletRequest) {
//            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
//            String callback = httpServletRequest.getParameter("callback");
//            if (callback != null && callback.trim().length() > 0) {
//                Object entity = containerResponseContext.getEntity();
//                JSONPObject jsonpObject = new JSONPObject(callback, entity);
//                containerResponseContext.setEntity(jsonpObject);
//                containerResponseContext.getHeaders().putSingle("Content-Type","text/javascript;charset=UTF-8");
//            }
//        }
    }

    @Override
    public void filter(ClientRequestContext clientRequestContext) throws IOException {
    }

    @Override
    public void filter(ClientRequestContext clientRequestContext, ClientResponseContext clientResponseContext) throws IOException {
    }

    @Override
    public Object aroundReadFrom(ReaderInterceptorContext readerInterceptorContext) throws IOException, WebApplicationException {
        Object result = readerInterceptorContext.proceed();
        return result;
    }

    @Override
    public void aroundWriteTo(WriterInterceptorContext writerInterceptorContext) throws IOException, WebApplicationException {
        writerInterceptorContext.proceed();
    }
}